# coding: utf-8
# @Author : lryself
# @Date : 2020/12/18 20:18
# @Software: PyCharm
import datetime

from flask import g, current_app
from sqlalchemy import or_

from ..models import db
from ..models.UserCollectModel import UserCollect
from ..utils import commons
from ..utils.response_code import RET


class UserCollectController(UserCollect):

    @classmethod
    def get(cls, **kwargs):
        information_id = kwargs.get("information_id")
        collect_id = kwargs.get("collect_id")
        user_id = kwargs.get("user_id") if kwargs.get("user_id") else g.user.user_id
        collect_type = kwargs.get("collect_type")

        filter_list = []
        filter_list.append(cls.IsDeleted == 0)
        filter_list.append(cls.userID == user_id)
        if information_id:
            filter_list.append(cls.informationID == information_id)
        if collect_type:
            filter_list.append(cls.type == int(collect_type))
        if collect_id:
            filter_list.append(cls.collectID == collect_id)

        try:
            result_model = db.session.query(cls.collectID,
                                            cls.title,
                                            cls.text,
                                            cls.informationID,
                                            cls.parentID,
                                            cls.type
                                            ).filter(*filter_list)
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，查询收藏信息失败', 'error': str(e)}

        if not result_model.first():
            return {"code": RET.DATAEXIST, "msg": "收藏不存在！"}

        return {"code": RET.OK, "msg": "查询成功！", "data": commons.query_to_dict(result_model.all())}

    @classmethod
    def add(cls, **kwargs):
        information_id = kwargs.get("information_id")
        title = kwargs.get("title")
        user_id = kwargs.get("user_id") if kwargs.get("user_id") else g.user.user_id
        collect_type = kwargs.get('type')
        parent_id = kwargs.get('parent_id')

        filter_list = []
        filter_list.append(cls.IsDeleted == 0)
        filter_list.append(cls.userID == user_id)
        filter_list.append(cls.type == int(collect_type))
        if collect_type == "1":
            pass
        elif collect_type == "2":
            pass
        elif int(collect_type) == 3:
            filter_list.append(cls.informationID == information_id)

        try:
            result_model = db.session.query(cls.collectID).filter(*filter_list)
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，查询收藏信息失败', 'error': str(e)}

        if result_model.first() and int(collect_type) == 3:
            return {"code": RET.DATAEXIST, "msg": "收藏已存在！"}

        if collect_type == '1':
            title = 'note_' + str(result_model.count() + 1)
        elif collect_type == '2':
            title = 'notefolder_' + str(result_model.count() + 1)

        try:
            collect_model = UserCollect(collectID=(datetime.datetime.now()).strftime('%Y%m%d%H%M%S'),
                                        userID=user_id,
                                        parentID=parent_id,
                                        title=title,
                                        informationID=information_id,
                                        type=collect_type)
            db.session.add(collect_model)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，添加收藏信息失败', 'error': str(e)}

        return {"code": RET.OK, "msg": "收藏成功！", "data": commons.query_to_dict(collect_model)}

    @classmethod
    def update(cls, **kwargs):
        user_id = kwargs.get("user_id") if kwargs.get("user_id") else g.user.user_id
        collect_type = kwargs.get('collect_type')
        collect_id = kwargs.get('collect_id')
        information_id = kwargs.get("information_id")

        filter_list = []
        filter_list.append(cls.IsDeleted == 0)
        filter_list.append(cls.userID == user_id)
        if collect_type:
            filter_list.append(cls.type == collect_type)
        if collect_id:
            filter_list.append(cls.collectID == collect_id)
        if information_id:
            filter_list.append(cls.informationID == information_id)

        try:
            result_model = db.session.query(cls).filter(*filter_list)

            if not result_model.first():
                return {'code': RET.NODATA, 'msg': '无数据'}

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，查询失败', 'error': str(e)}

        args = {}
        if kwargs.get("title"):
            args["title"] = kwargs.get("title")
        if kwargs.get("text"):
            args["text"] = kwargs.get("text")
        if kwargs.get("parent_id"):
            args["parentID"] = kwargs.get("parent_id")

        try:
            result_model.update(args)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，更新失败', 'error': str(e)}

        return {'code': RET.OK, 'msg': '更新成功'}

    @classmethod
    def delete(cls, **kwargs):
        information_id = kwargs.get("information_id")
        user_id = kwargs.get("user_id") if kwargs.get("user_id") else g.user.user_id
        collect_id = kwargs.get('collect_id')
        collect_type = kwargs.get("collect_type")

        filter_list = []
        filter_list.append(cls.IsDeleted == 0)
        filter_list.append(cls.userID == user_id)
        if information_id:
            filter_list.append(cls.informationID == information_id)
        if collect_type:
            filter_list.append(cls.type == int(collect_type))
        filter_list.append(or_(cls.collectID == collect_id, cls.parentID == collect_id))

        try:
            result_model = db.session.query(cls).filter(*filter_list)
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，查询收藏信息失败', 'error': str(e)}

        if not result_model.first():
            return {"code": RET.DATAEXIST, "msg": "收藏不存在！"}

        try:
            args = {"IsDeleted": 1}
            result_model.update(args)
            db.session.commit()

        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'msg': '数据库异常，修改收藏信息失败', 'error': str(e)}

        return {"code": RET.OK, "msg": "取消收藏成功！"}
